<?php
/**
 * Create By: PhpStorm
 * User: yuanxuncheng
 * File: Forgot.php
 * Date: 2017/1/2
 * Time: 23:13
 */

namespace app\api\model\page\user;

use app\api\model\dao\UserAccount;
use app\api\model\dao\UserAuths;
use think\Exception;
use app\library\Error;
use app\library\PageBase;
use think\Validate;
use app\library\Flag;
use think\Cache;
use app\library\Common;
use think\Log;

class Forgot extends PageBase
{

    private $objUserAccount;
    private $objUserAuths;

    public function __construct()
    {
        parent::__construct();

        $this->objUserAccount = new UserAccount();
        $this->objUserAuths = new UserAuths();
    }

    /**
     * @param $param
     * @return array|bool
     * @DESC 验证接口字段
     */
    public function checkParam($param)
    {
        $rule = [
            'identity_type' => 'require',
            'identifier' => 'require',
            'credential' => 'require',
            'verification_code' => 'require',
        ];
        $msg = [
            'identity_type.require' => '账号类型必填',
            'identifier.require' => '账号必填',
            'credential.require' => '密码必填',
            'verification_code.require' => '验证码必填',
        ];

        $validate = new Validate($rule, $msg);
        $result = $validate->check($param);
        if (!$result) {
            return $validate->getError();
        }
        return '';
    }

    public function excute($param)
    {

        // TODO:业务逻辑
        // 1、参数校验
        $ret = $this->checkParam($param);
        if ($ret) {
            Log::alert(__METHOD__ . ' param: ' . json_encode($param));
            return $this->getRes(Error::ERR_PARAM);
        }

        /// 手机号
        if (Flag::IDENTIFY_TYPE_PHONE == $param['identity_type']) {
            $ret = $this->objUserAccount->getUserAccountByPhone($param['identifier']);
            if (count($ret) == 0) {
                Log::alert(__METHOD__ . ' ret: ' . json_encode($param));
                return $this->getRes(Error::ERR_NOT_REGISTERED);
            }

            // 验证短信验证码
            $verfiyCode = Cache::get('sms:' . $param['identifier']);
            if ($param['verification_code'] != $verfiyCode) {
                Log::alert(__METHOD__ . ' ret: ' . json_encode($param));
                return $this->getRes(Error::ERR_VERIFY_CODE);
            }

            $credential = Common::encodePassword($param['credential']);
            $ret = $this->objUserAuths->updateUserAuths($param['identifier'], $param['identity_type'], $credential);

        }

        if (false === $ret) {
            Log::alert(__METHOD__ . ' ret: ' . json_encode($param));
            return $this->getRes(Error::ERR_SYS);
        }

        return $this->getRes();

    }
}
